package com.sevensoft.framework.context.support;

import com.sevensoft.framework.beans.factory.support.BeanDefinitionReader;
import com.sevensoft.framework.beans.factory.support.BeanDefinitionRegistry;
import com.sevensoft.framework.context.ApplicationContext;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ApplicationContext接口的字实现类，用于立即加载
 */
public abstract class AbstractApplicationContext implements ApplicationContext {

    /**
     * 声明解析器变量
     */
    protected BeanDefinitionReader beanDefinitionReader;

    /**
     * 定义用于存储bean对象的map容器
     */
    protected final Map<String, Object> singletonObjects = new ConcurrentHashMap<>();

    /**
     * 配置文件路径
     */
    protected String configLocation;

    /**
     * 进行配置文件加载并进行对象创建
     *
     * @throws Exception
     */
    @Override
    public void refresh() throws Exception {
        beanDefinitionReader.loadBeanDefinition(configLocation);
        finishBeanInitialization();
    }

    /**
     * bean初始化加载
     *
     * @throws Exception
     */
    private void finishBeanInitialization() throws Exception {
        //获取注册表对象
        BeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();

        //beanDefinition
        String[] beanDefinitionNames = registry.getBeanDefinitionNames();

        //bean初始化
        Arrays.stream(beanDefinitionNames).forEach(beanName -> {
            try {
                getBean(beanName);
            }
            catch (Exception ignored) {
            }
        });
    }
}
